<script setup>
import { computed, ref } from 'vue'
import { useFormState } from '@/composables/useFormState.js'
import { submitFormApi } from '@/apis/globalSbmitForm.js'
import { validateRequiredFields } from '@/utils/index.js'

const props = defineProps({
  api: {
    type: String,
    required: true,
  },
  requiredFields: {
    type: Array,
    default: () => [],
  },
  formData: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  isCustid: {
    // 是否需要携带custid
    type: Boolean,
    default: false,
  },
})

const requiredKeys = computed(() =>
  props.requiredFields.map((item) => item.key)
)

const { buttonType, buttonPlain } = useFormState(
  computed(() => props.formData),
  requiredKeys
)

const emit = defineEmits(['handleSuccess', 'beforeSubmit'])

const loading = ref(false)
const handlerSubmit = async () => {
  if (loading.value) return
  const { requiredFields, formData, api, isCustid } = props
  // 提交之前先发出事件
  emit('beforeSubmit')
  if (!validateRequiredFields(requiredFields, formData)) return
  try {
    const method = formData.id ? 'put' : 'post'
    await submitFormApi(api, method, formData, isCustid)
    uni.$u.toast('操作成功')
    emit('handleSuccess')
    setTimeout(() => {
      uni.navigateBack()
      loading.value = false
    }, 500)
  } catch {
    uni.$u.toast('操作失败')
  }
}
</script>

<template>
  <u-button
    @click="handlerSubmit"
    :loading="loading"
    :type="buttonType"
    :plain="!buttonPlain"
    shape="circle"
    >保存</u-button
  >
</template>
